package com.weng.bigdata.framework.jdbc.utils;

import com.weng.bigdata.core.jdbc.config.CustomDataSourceConfig;
import com.weng.framework.core.constants.GlobalConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CustomDataSourceUtils {

    private static volatile Map<String, CustomDataSourceConfig> map = new HashMap<>();

    public static CustomDataSourceConfig getInstance(String url) {
        String dataSourceName = getDataSourceName(url);
        if (map.containsKey(dataSourceName) && null != map.get(dataSourceName)) {
            CustomDataSourceConfig customDataSource = map.get(dataSourceName);
            if (null != customDataSource) {
                return customDataSource;
            }
        }
        return null;
    }

    public static CustomDataSourceConfig getCustomDataSource(String url) throws Exception {
        CustomDataSourceConfig customDataSource = getInstance(url);
        if (null != customDataSource) {
            try {
                Class<?> aClass = Class.forName(customDataSource.getDriver());
                if (null == aClass) {
                    throw new Exception("Unable to get driver instance for jdbcUrl: " + url);
                }
            } catch (ClassNotFoundException e) {
                throw new Exception("Unable to get driver instance: " + url);
            }
            return customDataSource;
        }
        return null;
    }



    private static String getDataSourceName(String jdbcUrl) {
        String dataSourceName = null;
        jdbcUrl = jdbcUrl.replaceAll(GlobalConstants.NEW_LINE_CHAR, GlobalConstants.EMPTY)
                .replaceAll(GlobalConstants.SPACE, GlobalConstants.EMPTY).trim().toLowerCase();
        String reg = "jdbc:\\w+";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(jdbcUrl);
        if (matcher.find()) {
            dataSourceName = matcher.group().split(GlobalConstants.COLON)[1];
        }
        return dataSourceName;
    }
}
